<?php
/**
 * @发布消息
 * @Author: Helloweba
 * @publish_direct.php
 */

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../config.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

$config = getConfig();
$exchange = 'article';


// connection -> channel -> exchange -> publish -> close

$connection = new AMQPStreamConnection(
    $config['host'],
    $config['port'],
    $config['user'],
    $config['password']
);

$channel = $connection->channel();

$channel->exchange_declare($exchange, 'direct', false, false, false);

// $cate = ['fantasy', 'military', 'history', 'romance'];
// $key = array_rand($cate);

$routing_key = $_GET['type'];

$data = json_encode([
    'id' => 'message_' . time(),
    'content' => 'type_'. $_GET['type']
]);

$msg = new AMQPMessage($data);

$channel->basic_publish($msg, $exchange, $routing_key);
$connection->reconnect();
$channel = $connection->channel();
// Send history message: {"id":"message_41","content":"type_history"}
echo 'Send '.$routing_key.' message: ' . $data . PHP_EOL;

$channel->close();
$connection->close();
